package org.devops

def recordProjectInfo(String execTime,String PROJECT_BASE_URL, String remoteDir, String fileName, Set<String> ansibleNames) {
    def nodeTools = new nodeTools()
    String branch = "${env.BRANCH}".replaceAll("origin/", "").replaceAll("_", "-").replaceAll("/", "-")
    String commit = sh(returnStdout: true, script: "git rev-parse --short HEAD").trim()
    String msg = sh(returnStdout: true, script: "git log --pretty=format:%s ${commit} -1").trim()

    def deleteCommands = []
    if (msg.contains("\"") || msg.contains("'")) {
        msg = msg.replaceAll("\"","").replaceAll("'","")
    }
    def curl = "curl -XPOST -H'Content-Type: application/json' ${PROJECT_BASE_URL}/projectInfo/add -d '{\"job_name\":\"${JOB_NAME}\",\"build_number\":\"${BUILD_NUMBER}\",\"env\":\"${ENV}\",\"service\": \"${SERVICE}\",\"app\": \"${APP}\",\"dir\": \"${remoteDir}\",\"file_name\": \"${fileName}\",\"exe_type\": \"node\",\"branch\": \"${branch}\",\"commit\": \"${commit}\",\"msg\":\"${msg}\",\"time\":\"${execTime}\"}'"
    String result = sh(returnStdout: true, script: "${curl}").trim()
    def resultJson = readJSON(text: result)
    def data = resultJson.data
    if (data.dir != "") {
        def deleteFile = "/data/app_repos/${data.env}/${data.service}/${data.app}/${data.dir}"
        echo "删除文件: $deleteFile"
        deleteCommands += "rm -rf ${deleteFile}"
    }

    //删除ansible上超过5次的记录
    if (deleteCommands.size() > 0) {
        String deleteCommand = deleteCommands.join("\r\n")
        for (ansibleName in ansibleNames) {
            nodeTools.remoteExec(ansibleName, "${deleteCommand}")
        }
    }
}

def recordImageProjectInfo(String execTime,String PROJECT_BASE_URL, String appName,String imageName) {
    String jobName = "${env.JOB_NAME}"
    String branch = "${env.BRANCH}".replaceAll("origin/", "").replaceAll("_", "-").replaceAll("/", "-")
    String commit = sh(returnStdout: true, script: "git rev-parse --short HEAD").trim()
    String msg = sh(returnStdout: true, script: "git log --pretty=format:%s ${commit} -1").trim()

    def curl = "curl -XPOST -H'Content-Type: application/json' ${PROJECT_BASE_URL}/projectInfo/add -d '{\"job_name\":\"${jobName}\",\"build_number\":\"${BUILD_NUMBER}\",\"env\":\"${ENV}\",\"service\": \"${SERVICE}\",\"app\": \"${appName}\",\"file_name\": \"${imageName}\",\"exe_type\": \"k8s\",\"branch\": \"${branch}\",\"commit\": \"${commit}\",\"msg\":\"${msg}\",\"time\":\"${execTime}\"}'"
    String result = sh(returnStdout: true, script: "${curl}").trim()
}

def getProjectInfoByBuildNumber(String PROJECT_BASE_URL, String buildNumber) {
    def curl = "curl ${PROJECT_BASE_URL}/projectInfo/getByBuildNumber?job_name=${JOB_NAME}\\&build_number=${buildNumber}"
    String result = sh(returnStdout: true, script: "${curl}").trim()
    def resultJson = readJSON(text: result)
    return resultJson.data
}
